#!/usr/bin/python
#-*-coding:utf-8 -*-


import os
import sys
import time
from PyQt4 import QtGui, QtCore

from preprocessor import Preprocessor
import qt4gui
import gettext
import database2

SEP = os.sep

IDIR = "images"
GETTEXT_DIR = "locale"
SPLASH_IMAGE = IDIR+SEP+"kuklopsz.jpg"
#WINDOW_ICON = IDIR+SEP+"kicsikuklopsz.ico"
WINDOW_ICON = IDIR+SEP+"kicsikuklopsz.gif"
STATIC_SYSTRAYICON = IDIR+SEP+"kicsikuklopsz.gif"
MOVIE_ICON = IDIR+SEP+"pislokuklopsz.gif"

gettext.install("cyklory", localedir=GETTEXT_DIR, unicode=True)

class SystemTrayIcon(QtGui.QSystemTrayIcon):
  def __init__(self, icon, parent=None, win=None):
    QtGui.QSystemTrayIcon.__init__(self, icon, parent)
    menu = QtGui.QMenu(parent)
    exitAction = menu.addAction(_("Exit"), self.exit)
    self.setContextMenu(menu)
    QtCore.QObject.connect(self, QtCore.SIGNAL("activated(QSystemTrayIcon::ActivationReason)"), self.katt)
    self.win = win
  def exit(self):
    print _("Exit")
    sys.exit()
  def katt(self, r):
    if r == QtGui.QSystemTrayIcon.DoubleClick or r == QtGui.QSystemTrayIcon.Trigger:
      if self.win.isVisible():
        self.win.hide()
      else:
        self.win.show()

class Window():
  def centerOnScreen (self):
    resolution = QtGui.QDesktopWidget().screenGeometry()
    self.move((resolution.width() / 2) - (self.frameSize().width() / 2),(resolution.height() / 2) - (self.frameSize().height() / 2))
    
class Ui_MainWindow(Window, QtGui.QMainWindow, qt4gui.Ui_MainWindow):
  def __init__(self):
    QtGui.QMainWindow.__init__(self)
    qt4gui.Ui_MainWindow.__init__(self)
    self.db = database2.CykloryDB()
    self.prep = Preprocessor()
    self.prep.start()
    self.setupUi(self)
    self.centerOnScreen()
    self.load_combo("mem_s_combo", "subjects")
    self.load_combo("edit_c_s_combo", "subjects")
    self.load_combo2("edit_c_lang_combo", ["hu","en","fr","it"])
    
    QtCore.QObject.connect(self.mem_s_combo, QtCore.SIGNAL("currentIndexChanged(int)"), self.selected_mem_s_combo)
    QtCore.QObject.connect(self.mem_s_slider, QtCore.SIGNAL("valueChanged(int)"), self.changed_mem_s_slider)

    QtCore.QObject.connect(self.mem_c_combo, QtCore.SIGNAL("currentIndexChanged(int)"), self.selected_mem_c_combo)

    QtCore.QObject.connect(self.mem_s_combo, QtCore.SIGNAL("currentIndexChanged(int)"), self.selected_mem_c_combo)

    QtCore.QObject.connect(self.edit_c_s_combo, QtCore.SIGNAL("currentIndexChanged(int)"), self.selected_edit_c_s_combo)
    QtCore.QObject.connect(self.edit_c_c_combo, QtCore.SIGNAL("currentIndexChanged(int)"), self.selected_edit_c_c_combo)

    QtCore.QObject.connect(self.mem_sp_soundfile_button, QtCore.SIGNAL("clicked()"), self.mem_sp_soundfile_button_clicked)
    QtCore.QObject.connect(self.mem_sp_tool_button, QtCore.SIGNAL("clicked()"), self.mem_sp_tool_button_clicked)

    QtCore.QObject.connect(self.mem_start_button, QtCore.SIGNAL("clicked()"), self.mem_start_button_clicked)
    QtCore.QObject.connect(self.mem_stop_button, QtCore.SIGNAL("clicked()"), self.mem_stop_button_clicked)
    QtCore.QObject.connect(self.mem_edit_button, QtCore.SIGNAL("clicked()"), self.mem_edit_button_clicked)

    QtCore.QObject.connect(self.edit_c_add_button, QtCore.SIGNAL("clicked()"), self.edit_c_add_button_clicked)
    QtCore.QObject.connect(self.edit_c_lang_button, QtCore.SIGNAL("clicked()"), self.edit_c_lang_button_clicked)
    QtCore.QObject.connect(self.edit_c_wait_button, QtCore.SIGNAL("clicked()"), self.edit_c_wait_button_clicked)
    QtCore.QObject.connect(self.edit_c_rep_button, QtCore.SIGNAL("clicked()"), self.edit_c_rep_button_clicked)

    QtCore.QObject.connect(self.edit_s_add_button, QtCore.SIGNAL("clicked()"), self.edit_s_add_button_clicked)


  def load_combo(self, name, dbget, args=''):
    if args != '': args = "'"+str(args)+"'"
    eval("self."+name+".clear()")
    elements = [(-1, _("--- choose ---"))] + eval("self.db.get_"+dbget+"("+args+")")
    map(eval("self."+name+".addItem"), map(lambda e: e[1], elements), map(lambda e: e[0], elements))

  def load_combo2(self, name, values):
    eval("self."+name+".clear()")
    elements = [(-1, _("--- choose ---"))] + map(lambda x, y: (x,y), values, values)
    map(eval("self."+name+".addItem"), map(lambda e: e[1], elements), map(lambda e: e[0], elements))
    
  def mem_start_button_clicked(self):
    self.prep.start_espeak()
    self.mem_start_button.setEnabled(False)
    self.mem_stop_button.setEnabled(True)

  def mem_stop_button_clicked(self):
    self.prep.stop_espeak()
    self.mem_start_button.setEnabled(True)
    self.mem_stop_button.setEnabled(False)

  def mem_edit_button_clicked(self):
    s = self.mem_s_combo.currentIndex()
    c = self.mem_c_combo.currentIndex()
    self.edit_c_s_combo.setCurrentIndex(s)
    self.edit_c_c_combo.setCurrentIndex(c)
    self.tabWidget.setCurrentIndex(2)
    self.edit_toolbox.setCurrentIndex(1)
    self.edit_c_textedit.setFocus()    

  def mem_sp_tool_button_clicked(self):
    file_name = QtGui.QFileDialog.getOpenFileName(self, _('Open file'), os.environ['HOME'])
    self.mem_sp_lineedit.setText(file_name)

  def mem_sp_soundfile_button_clicked(self):
    self.prep.save_soundfile(self.mem_sp_lineedit.text())
    
  def changed_mem_s_slider(self, value):
    new_value = 80+value*3
    self.mem_s_lcd.display(new_value)
    self.prep.set_speed(new_value)
    self.mem_stop_button_clicked()

  def edit_s_add_button_clicked(self):
    le = unicode(self.edit_s_lineedit1.text())
    if len(le) != 0:
      self.db.new("Subjects", le)

  def edit_c_lang_button_clicked(self):
    lang = str(self.edit_c_lang_combo.itemData(self.edit_c_lang_combo.currentIndex()).toString())
    cur = self.edit_c_textedit.textCursor()
    t = cur.selectedText()
    cur.removeSelectedText()
    cur.insertText("<@lang="+lang+"@>"+t+"<@/lang@>")
    self.edit_c_textedit.setFocus()    

  def edit_c_wait_button_clicked(self):
    w = self.edit_c_wait_spinbox.value()
    cur = self.edit_c_textedit.textCursor()
    cur.insertText("<@wait="+str(w)+"@>")
    self.edit_c_textedit.setFocus()    

  def edit_c_rep_button_clicked(self):
    r = self.edit_c_rep_spinbox.value()
    cur = self.edit_c_textedit.textCursor()
    t = cur.selectedText()
    cur.removeSelectedText()
    cur.insertText("<@rep="+str(r)+"@>"+t+"<@/rep@>")
    self.edit_c_textedit.setFocus()    

  def edit_c_add_button_clicked(self):
    le = unicode(self.edit_c_lineedit.text())
    da = unicode(self.edit_c_textedit.toPlainText())
    su = str(self.edit_c_s_combo.itemData(self.edit_c_s_combo.currentIndex()).toString())
    t = map(lambda e: e[1], self.db.get_curriculums(su))
    if (len(le) != 0) and (len(da) != 0):
      cu = str(self.edit_c_c_combo.itemData(self.edit_c_c_combo.currentIndex()).toString())
      if cu != "-1":
        print "Módosítjuk"
        self.db.set("Curriculums", cu, {"name":le, "data":da})
      elif (le not in t):
        self.db.new("Curriculums", [su, le, da])
        print "Hozzáadjuk"


  def selected_mem_s_combo(self, x):
    v = self.mem_s_combo.itemData(x).toString()
    if v != '-1' and v != '':
      self.mem_c_combo.setEnabled(True)
      self.load_combo("mem_c_combo", "curriculums", v)
    else:
      self.mem_start_button.setEnabled(False)
      self.mem_stop_button.setEnabled(False)
      self.mem_edit_button.setEnabled(False)
      self.mem_c_combo.setEnabled(False)
      self.mem_c_combo.setCurrentIndex(0)
      self.mem_webview.setHtml("")
    self.prep.stop_espeak()

  def selected_mem_c_combo(self, x):
    v = self.mem_c_combo.itemData(x).toString()
    print "v", v
    if v != '-1' and v != '':
      self.prep.set_source(self.db.get_curdata(v))
      self.mem_webview.setHtml(self.prep.get_text())
      self.mem_start_button.setEnabled(True)
#      self.mem_stop_button.setEnabled(True)
      self.mem_edit_button.setEnabled(True)
    else:
      self.mem_webview.setHtml("")
      self.mem_start_button.setEnabled(False)
      self.mem_stop_button.setEnabled(False)
      self.mem_edit_button.setEnabled(False)
    self.prep.stop_espeak()
      

  def selected_edit_c_s_combo(self, x):
    v = self.edit_c_s_combo.itemData(x).toString()
    if v != '-1' and v != '':
      self.edit_c_c_combo.setEnabled(True)
      self.edit_c_lineedit.setEnabled(True)
      self.edit_c_add_button.setEnabled(True)
      self.load_combo("edit_c_c_combo", "curriculums", v)
    else:
      self.edit_c_lineedit.setEnabled(False)
      self.edit_c_add_button.setEnabled(False)
      self.edit_c_c_combo.setEnabled(False)
      self.edit_c_c_combo.setCurrentIndex(0)

  def selected_edit_c_c_combo(self, x):
    v = self.edit_c_c_combo.itemData(x).toString()
    if v != '-1' and v != '':
      self.edit_c_textedit.setPlainText(self.db.get_curdata(v))
      self.edit_c_lineedit.setText(self.edit_c_c_combo.itemText(x))
      self.edit_c_remove_button.setEnabled(True)
    else:
      self.edit_c_textedit.setPlainText("")
      self.edit_c_lineedit.setText("")
      self.edit_c_remove_button.setEnabled(False)

class WaitLoad(QtCore.QThread):
  def __init__(self, p):
    QtCore.QThread.__init__(self)
    self.p = p
  def __del__(self):
    self.wait()
  def run(self):
    while True:
      time.sleep(1)
      try:
        if self.p.trayIcon.isVisible:
          time.sleep(2)
          self.emit(QtCore.SIGNAL("waitload_signal()"))
          break
      except:
        pass

class Main():
  def __init__(self):
    app = QtGui.QApplication(sys.argv)
    app.setWindowIcon(QtGui.QIcon(WINDOW_ICON))
    splash_pixmap=QtGui.QPixmap(SPLASH_IMAGE);
    self.splash = QtGui.QSplashScreen(splash_pixmap);
    self.splash.show()
    w = QtGui.QWidget()
    self.wl = WaitLoad(self)
    self.wl.start()
    self.wl.connect(self.wl, QtCore.SIGNAL("waitload_signal()"), self.start_main_window)
    self.main_window = Ui_MainWindow()
    self.static_systrayicon = QtGui.QIcon(STATIC_SYSTRAYICON)
    self.movie_icon = QtGui.QMovie(MOVIE_ICON)
    self.trayIcon = SystemTrayIcon(self.static_systrayicon, w, self.main_window)
    self.trayIcon.setToolTip(_("Click right button"))
    self.trayIcon.show()
    self.movie_icon.connect(self.movie_icon, QtCore.SIGNAL("frameChanged(int)"), self.update_systrayicon)
    self.movie_icon.start()
    sys.exit(app.exec_())
     
  def update_systrayicon(self):
    current_icon = QtGui.QIcon(self.movie_icon.currentPixmap())
    self.trayIcon.setIcon(current_icon)
    
  def start_main_window(self):
    self.main_window.show()
    self.splash.finish(self.main_window)
    
if __name__ == '__main__':
    Main()
